package xyz.hubery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import xyz.hubery.domain.SysUser;
import xyz.hubery.domain.SysUserRole;
import xyz.hubery.feign.AdminServiceFeign;
import xyz.hubery.model.R;
import xyz.hubery.service.SysUserRoleService;
import xyz.hubery.service.SysUserService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/users")
@Api(tags = "员工管理")
public class UsersController implements AdminServiceFeign {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserRoleService userRoleService;


    @GetMapping
    @ApiOperation(value = "条件分页查询员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "分页对象"),
            @ApiImplicitParam(name = "user",value = "条件对象")
    })
    @PreAuthorize("hasAuthority('sys_user_query')")
    public R<Page<SysUser>> queryPage(Page<SysUser> page,SysUser user) {
        page.addOrder(OrderItem.desc("last_update_time"));
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(user.getFullname()),SysUser::getFullname,user.getFullname());
        wrapper.like(!StringUtils.isEmpty(user.getMobile()),SysUser::getMobile,user.getMobile());
        wrapper.eq(!StringUtils.isEmpty(user.getStatus()),SysUser::getStatus,user.getStatus());
        Page<SysUser> sysUserPage = userService.page(page, wrapper);
        // 封装角色信息
        List<SysUser> sysUsers = sysUserPage.getRecords();
        for (SysUser sysUser : sysUsers) {
            userRoleService.addRoleOfUser(sysUser);
        }

        return R.ok(sysUserPage);
    }


    @PostMapping
    @PreAuthorize("hasAuthority('sys_user_create')")
    @ApiOperation(value = "新增员工")
    @ApiImplicitParam(name = "user",value = "员工json数据")
    public R addUser(@RequestBody SysUser user) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        Long userId = user.getId();
        String role_strings = user.getRole_strings();
        String[] ids = role_strings.split(",");
        List<Long> roleIds = new ArrayList<>();
        for (String id : ids) {
            roleIds.add(Long.valueOf(id));
        }
        userRoleService.addUserRoles(userId,roleIds);
        return R.ok();
    }


    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys_user_delete')")
    @ApiOperation(value = "删除员工")
    @ApiImplicitParam(name = "ids",value = "员工id列表")
    public R deleteUsers(@RequestBody List<Long> ids) {
        userService.delUsers(ids);
        return R.ok();
    }


    @PatchMapping("/update")
    @PreAuthorize("hasAuthority('sys_user_update')")
    @ApiOperation(value = "修改员工")
    @ApiImplicitParam(name = "user",value = "员工json数据")
    public R updateUser(@RequestBody SysUser user) {
        userService.updateUser(user);
        return R.ok();
    }

    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('sys_user_query')")
    @ApiOperation(value = "查询员工信息")
    @ApiImplicitParam(name = "userId",value = "员工id")
    public R<SysUser> querUserDetails(@PathVariable("userId") Long userId){
        SysUser user = userService.findUserById(userId);
        return R.ok(user);
    }

    @GetMapping("/admin-name/{adminId}")
    @Override
    public String getAdminName(@PathVariable Long adminId) {
        SysUser admin = userService.getById(adminId);
        if(admin == null) {
            throw new IllegalArgumentException("无效的管理员ID");
        }
        return admin.getUsername();
    }
}
